package com.mengshu.token.storage;

import com.mengshu.token.api.LoginUser;
import com.mengshu.token.consts.TokenConsts;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *     redis存储token
 * </p>
 *
 * @author liuning
 * @date 11:00 下午 2022/1/28
 */
@RequiredArgsConstructor
public class RedisUserStorage implements UserStorage {

    private final RedisTemplate<String, LoginUser> redisTemplate;

    private final static TimeUnit TIME_UNIT = TokenConsts.STORAGE_TIME_UNIT;

    @Override
    public LoginUser get(String token) {
        return redisTemplate.opsForValue().get(token);
    }

    @Override
    public LoginUser get(String token, long timeout) {
        final LoginUser loginUser = redisTemplate.opsForValue().get(token);
        if (loginUser != null) {
            redisTemplate.expire(token, timeout, TIME_UNIT);
        }
        return loginUser;
    }

    @Override
    public Set<String> pattern(String pattern) {
        return redisTemplate.keys(pattern);
    }

    @Override
    public void set(String token, LoginUser loginUser, long timeout) {
        redisTemplate.opsForValue().set(token, loginUser, timeout, TIME_UNIT);
    }

    @Override
    public void set(String token, LoginUser loginUser) {
        redisTemplate.opsForValue().set(token, loginUser);
    }

    @Override
    public void del(String token) {
        redisTemplate.delete(token);
    }
}
